package net.caixiaomi.info.ui.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.baidu.mobstat.StatService;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.ArticleAdapter;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.ArticleItem;
import net.caixiaomi.info.model.ArticlePageModel;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.details.ArticleDetailActivity;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.widgets.DefLoading;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;
import net.caixiaomi.smartrefresh.layout.api.RefreshLayout;
import net.caixiaomi.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;
import retrofit2.Call;

public class CollectActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener, OnRefreshListener {

    @BindView(R.id.refresh)
    SmartRefreshLayout mRefresh;

    @BindView(android.R.id.list)
    RecyclerView mListView;

    @BindView(R.id.progress)
    CircularProgressBar mProgress;

    @BindView(R.id.btn_setting)
    TextView btn_setting;


    private ArticleAdapter mAdapter;
    private int mPageNum = 1;
//    private MenuItem mEditMenu;
    private int mHandlePosition = -1;
    private String mRelateArticleId;

    @Override
    protected int layout() {
        return R.layout.act_collect;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mRelateArticleId = getIntent().getStringExtra("data");
        if (!TextUtils.isEmpty(mRelateArticleId)) {
            setTitle(R.string.C_MORE_ARTICLE);
        }
        super.onCreate(savedInstanceState);
        mLoading = new DefLoading(this);
        mRefresh.setOnRefreshListener(this);
        mListView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ArticleAdapter(null);
        mAdapter.setOnLoadMoreListener(this, mListView);
        TextView textView = (TextView) LayoutInflater.from(this).inflate(R.layout.empty, null);
        textView.setText(!TextUtils.isEmpty(mRelateArticleId) ? R.string.C_COUPONS_EMPTY : R.string.C_NO_MINE_COLLECT_DATA);
        mAdapter.setEmptyView(textView);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);

        mListView.setAdapter(mAdapter);

        loadData();

        btn_setting.setText(getResources().getString(R.string.C_EDIT));
        btn_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String title = btn_setting.getText().toString();
                String edit = getString(R.string.C_EDIT);
                if (TextUtils.equals(title, edit)) {
                    btn_setting.setText(R.string.C_CANCEL);
                    mAdapter.setEdit(true);
                } else {
                    btn_setting.setText(R.string.C_EDIT);
                    mAdapter.setEdit(false);
                }
            }
        });
    }

    private void loadData() {
        JSONObject params = new JSONObject();
        params.put("pageNum", mPageNum);
        params.put("pageSize", Constants.PAGE_SIZE);
        if (!TextUtils.isEmpty(mRelateArticleId)) {
            params.put("currentArticleId", mRelateArticleId);
        }
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<ArticlePageModel>> baseCallModelCall = TextUtils.isEmpty(mRelateArticleId) ? requestService.collectList(params) : requestService.relatedArticles(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<ArticlePageModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<ArticlePageModel> data) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                ArticlePageModel model = data.data;
                if (model != null) {
                    List<ArticleItem> list = model.getList();
//                    mEditMenu.setVisible(TextUtils.isEmpty(mRelateArticleId) && !list.isEmpty());
                    if (mPageNum == 1) {
                        mAdapter.getData().clear();
                    }
                    mAdapter.addData(list);
                    boolean hasNextPage = Boolean.valueOf(model.getHasNextPage());
                    mAdapter.setEnableLoadMore(hasNextPage);
                    mAdapter.loadMoreComplete();
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                if (mPageNum != 1) {
                    mAdapter.loadMoreComplete();
                }
                mPageNum = mAdapter.getData().size() % Integer.valueOf(Constants.PAGE_SIZE) == 0 ? mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) : mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) + 1;
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }
            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                if (mPageNum != 1) {
                    mAdapter.loadMoreComplete();
                }
                mPageNum = mAdapter.getData().size() % Integer.valueOf(Constants.PAGE_SIZE) == 0 ? mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) : mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) + 1;
            }
        });
    }

    private void toDelete() {
        if (mHandlePosition == -1)
            return;
        mLoading.show();
        ArticleItem item = (ArticleItem) mAdapter.getData().get(mHandlePosition);
        JSONObject params = new JSONObject();
        params.put("id", item.getArticleId());
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel> baseCallModelCall = requestService.collectDelete(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel>(this) {
            @Override
            public void onSuccess(BaseCallModel data) {
                mLoading.dismiss();
                mAdapter.remove(mHandlePosition);
                ToastUtil.s(data.msg);
            }

            @Override
            public void onFail(ResponseError error) {
                mLoading.dismiss();
                ToastUtil.s(error.getMessage());
            }

            @Override
            public void onError() {
                mLoading.dismiss();
            }
        });
    }

//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.edit, menu);
//        mEditMenu = menu.findItem(R.id.btn_edit);
//        mEditMenu.setVisible(false);
//        return true;
//    }
//
//    public boolean onPrepareOptionsMenu(Menu menu) {
//        return true;
//    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                onBackPressed();
                break;
            case R.id.btn_edit:
//                String title = mEditMenu.getTitle().toString();
//                String edit = getString(R.string.C_EDIT);
//                if (TextUtils.equals(title, edit)) {
//                    mEditMenu.setTitle(R.string.C_CANCEL);
//                    mAdapter.setEdit(true);
//                } else {
//                    mEditMenu.setTitle(R.string.C_EDIT);
//                    mAdapter.setEdit(false);
//                }

                break;
        }
        return true;
    }

    @Override
    public void onLoadMoreRequested() {
        mPageNum++;
        loadData();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        try {
            mHandlePosition = position;
            toDelete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        try {
            if (mAdapter.isEdit()) {
                return;
            }
            ArticleItem item = (ArticleItem) adapter.getData().get(position);
            Intent intent = new Intent(this, ArticleDetailActivity.class);
            intent.putExtra("data", item.getArticleId());
            startActivity(intent);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "wodeshoucang-view");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "wodeshoucang-view");
    }

    @Override
    public void onBackPressed() {
        AppHelper.sendStatistics(TextUtils.isEmpty(mRelateArticleId) ? "wdscfanhui" : "");
        super.onBackPressed();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPageNum = 1;
        loadData();
    }
}
